package api

import (
	"context"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
	fromData "user_api/api_structure"
	"user_api/global"
	"user_api/middlewares"
	proto "user_api/proto"
	myvalidator "user_api/validator"
)

func Login(ctx *gin.Context) {
	LoginForm := fromData.LoginForm{}

	if err := ctx.ShouldBind(&LoginForm); err != nil {
		myvalidator.HandleValidatorError(ctx, err)
		return
	}

	userData, err := global.UserSrvClient.GetUserInfoByAccount(context.TODO(), &proto.RequestAccount{Account: LoginForm.Account})
	zap.S().Debug("查询用户信息", userData)
	if err != nil {
		zap.S().Errorf("不存在有效用户信息", err.Error())
		global.ReturnMsg(ctx, http.StatusInternalServerError, "no", err)
		return
	}

	ChkPassWord, err := global.UserSrvClient.GetPassword(context.TODO(), &proto.RequestPassword{Password: LoginForm.PassWord, EncryptedPassword: userData.PassWord})

	zap.S().Debug("查询密码", ChkPassWord)
	if err != nil {
		zap.S().Errorf("获取密码失败", err.Error())
		global.ReturnMsg(ctx, http.StatusInternalServerError, "no", err)
		return
	}

	if ChkPassWord.Code != true {
		zap.S().Debug("数据库密码", ChkPassWord.Code)

		global.ReturnMsg(ctx, http.StatusForbidden, "no", "密码错误")
		return
	}
	j := middlewares.NewJWT()
	claims := global.CustomClaims{
		ID:          uint(userData.Id),
		AccountName: userData.UserName,
		AuthorityId: uint(userData.Role),
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),               //签名的生效时间
			ExpiresAt: time.Now().Unix() + 60*60*24*30, //30天过期
			Issuer:    "hypercube",
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		zap.S().Errorf("[PasswordLogin] 生成token失败失败: %s", err.Error())
		global.ReturnMsg(ctx, http.StatusInternalServerError, "no", "生成token失败")
		return

	} else {
		data := make(map[string]interface{})
		data["expired_at"] = (time.Now().Unix() + 60*60*24*30) * 1000
		data["name"] = userData.UserName
		data["token"] = token

		global.ReturnMsg(ctx, http.StatusOK, "ok", data)
		return
	}

}
